const appInstance = getApp()
var globalData = appInstance.globalData
const common = require('../../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    diet_bg: '/images/diet/record_bg.jpg',  //饮食记录背景图片
    upload_img: '/images/diet/upload_button.png',
    notice: '记录自己的饮食记录，便于系统为你提出更好的建议，赶快行动吧!',
    username: '用户',
    specific_time: '具体时间',
    time_slot: '时间段',
    food_name: '食物名称',
    caloric: '热量',
    quantity: '数量',
    upload_notice: '点击左侧上传图片',
    selectArray: [
      {
        "id": "10",
        "text": "上午"
      }, {
        "id": "21",
        "text": "下午"
      },
      {
        "id": "21",
        "text": "晚上"
      },
    ],
    validateNotice: '',
    isHidden: true, // 是否隐藏验证提示，false：不隐藏
    username_value: '', // 系统提供的用户名值
    specific_value: '', // 系统提供的具体时间值
    UploadImageURL: '', // 要上传图片的后台地址
    requestURL: 'http://localhost:8081/keepfit/addDiet',// 请求地址
    nowText: '请选择',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // 这里需要对全局数据中的 ifChoose和 selectItem进行清空，以获取最新的值
    globalData.ifChoose = false
    globalData.selectItem = null
    // 获取具体时间和用户名
    that.setData({
      username_value: that.getCurrentUsername(),
      specific_value: that.getSubmitTime()
    })
  },
  // 处理下拉菜单
  HandleDropMenu(e) {
    console.log(globalData.ifChoose)
    console.log(globalData.selectItem)
  },
  // 表单提交
  HandleForm(e) {
    var that = this
    console.log(e)
    var endValidateResult = false  // 最终校验结果
    var food_Name = e.detail.value.food_name
    var caloric = e.detail.value.caloric
    var quantity = e.detail.value.quantity
    console.log(food_Name + " " + caloric + " " + quantity + " ")

    // 用于校验部分格式
    var parms = {
      food_Name: food_Name,
      caloric: caloric,
      quantity: quantity,
    }

    if (that.valiInputDate(parms)) {
      endValidateResult = true
      var result = that.JudgeisAllSelected(e)
      if (!result) {
        console.log('输入不能为空！')
        that.setData({
          isHidden: false
        })
        that.setData({
          validateNotice: '输入不能为空！'
        })
      }
    } else {
      var result = that.JudgeisAllSelected(e)
      if (!result) {
        console.log('输入不能为空！')
        that.setData({
          isHidden: false
        })
        that.setData({
          validateNotice: '输入不能为空！'
        })
      }
      endValidateResult = false
    }

    // 格式校验正确
    if (endValidateResult && result) {
      // 全部表单的参数
      var AllParms = {
        username: that.data.username_value,
        specific_time: that.data.specific_value,  // 具体时间
        food_name: food_Name,
        caloric: caloric,
        quantity: quantity,
        time_slot: globalData.selectItem,
        img_url: that.data.UploadImageURL,  // 上传的食物图片地址
      }
      // 调用后台接口对数据进行上传
      // var requestResult=
      common.addDiet(AllParms, that.data.requestURL)
        .then(res => {
          if (res == 'success') {
            wx.showToast({
              title: '上传成功！',
              icon: 'success',
            })
            that.setData({
              UploadImageURL: '',
              upload_img:'/images/diet/upload_button.png',
            })

          } else {
            wx.showToast({
              title: '上传失败！',
              icon: 'fail',
            })
          }
        })
      that.setData({
        isHidden: true
      })
    } else {
      wx.showToast({
        title: '上传失败！',
        icon: 'error',
      })
      that.setData({
        isHidden: false
      })
      console.log("isHidden=" + that.data.isHidden)
    }

  },
  /* 使用正则判断输入是否合法  validateFlag:要校验的标记（即校验的名称）
  */
  valiInputDate(parms) {
    var that = this
    var pattern_foodName = /([0-9]|[A-z])/i
    var pattern_number = /([0-9]|[.])/i

    var foodName_validateResult = false  // 校验结果
    var caloric_validateResult = false    // 热量校验结果
    var quantity_validateResult = false    // 数量校验结果
    var uploadImageResult = false   // 图片上传校验结果


    // 下面是三个需要校验的数据
    var food_Name = parms.food_Name
    var caloric = parms.caloric
    var quantity = parms.quantity


    //  对于食物名称 只能是 字母、数字、中文
    for (var i = 0; i < food_Name.length; i++) {
      if (!(pattern_foodName.test(food_Name[i]) || that.isChinese(food_Name[i]))) {
        foodName_validateResult = false
        that.setData({
          validateNotice: '食物名称只能是字母、数字、中文'
        })
        return foodName_validateResult
      } else {
        foodName_validateResult = true
      }
    }


    // 如果食物名称校验正确的话
    if (foodName_validateResult) {
      // 对于热量和数量  只能是 数字、小数点
      for (var i = 0; i < parms.caloric.length; i++) {
        if (parms.caloric[0] == '.' || parms.caloric[parms.caloric.length - 1] == '.') {
          that.setData({
            validateNotice: '热量和数量的开头和结尾不能是小数点！'
          })
          caloric_validateResult = false
          return caloric_validateResult
        } else {
          if (!(pattern_number.test(parms.caloric[i]))) {
            caloric_validateResult = false
            that.setData({
              validateNotice: '热量/数量格式只能为数字、小数点！'
            })
            return caloric_validateResult
          } else {
            caloric_validateResult = true
          }
        }
      }
      if (caloric_validateResult) {
        // 对数量进行校验
        for (var i = 0; i < quantity.length; i++) {
          if (quantity[0] == '.' || quantity[quantity.length - 1] == '.') {
            that.setData({
              validateNotice: '热量和数量的开头和结尾不能是小数点！'
            })
            quantity_validateResult = false
            return quantity_validateResult
          } else {
            if (!(pattern_number.test(quantity[i]))) {
              quantity_validateResult = false
              that.setData({
                validateNotice: '热量/数量格式只能为数字、小数点！'
              })
              return quantity_validateResult
            } else {
              quantity_validateResult = true
            }
          }
        }
      }
    }
    if (quantity_validateResult) {
      if (that.data.UploadImageURL == '' || that.data.UploadImageURL == null) {
        uploadImageResult = false
        that.setData({
          validateNotice: '图片未上传!!'
        })
        return uploadImageResult
      } else {
        uploadImageResult = true
      }
    }
    return uploadImageResult

  },
  // 判断输入文本中是否含有中文
  isChinese(temp) {
    if (escape(temp).indexOf("%u") < 0) {
      return false
    } else {
      return true
    }


  },
  // 判断用户是否全部已选
  JudgeisAllSelected(e) {
    var result = false
    var parm = e.detail.value


    //  如果下拉菜单选中了的话
    if (globalData.ifChoose) {
      for (var index in parm) {
        if (parm[index] != null && parm[index] != '') {
          result = true
        } else {
          result = false
          break
        }
      }
    } else {
      result = false
    }
    return result
  },
  HandleReset() {
    var that = this
    that.setData({
      isHidden: true,
      username_value: that.getCurrentUsername(),
      specific_value: that.getSubmitTime(),
      nowText: '请选择',
      UploadImageURL:'',
    })
  },
  // 获取提交时间
  getSubmitTime() {
    var Time = ""
    var time = new Date()

    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()
    var hour = time.getHours()
    var minute = time.getMinutes()

    if(month>=10 && month<=12){
      month=month
    }else{
      month='0'+month
    }

    if(day>=10 && day<=12){
      day=day
    }else{
      day='0'+day
    }

    Time = year + "-" + month + "-" + day + " " + hour + ":" + minute
    return Time
  },
  // 从本地缓存获取用户名
  getCurrentUsername() {
    var username = ''
    username = wx.getStorageSync('userMessage').user
    return username
  },
  //点击上传图片按钮
  HandleUploadImage() {
    var that = this
    var fileID = ''
    common.uploadImage()
      .then(res => {  // res:返回上传图片的在后台ID
        fileID = res
        return res
      }).then(res => {
        // 通过图片ID获取图片真实地址
        common.getImageRealURL(fileID)
          .then(res => {
            that.setData({
              UploadImageURL: res,
              upload_img:res
            })
            console.log('图片的地址=' + that.data.UploadImageURL)
          })
      })

  },
  HandleInput(){
    var that=this
    that.setData({
      isHidden:true
    })
  }
})